/*
 * ProfileHandler.java
 *
 * Created on December 2, 2006, 3:36 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.asaga.tools;

import java.beans.*;
import java.io.Serializable;
import java.util.Date;
import java.util.ArrayList;
import java.sql.*;
import java.util.*;
import org.apache.tools.ant.taskdefs.Java;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author jeremys
 */
public class ProfileHandler {
    //database objects
    private DBPool connectionPool;
    private java.sql.Statement statement;
    private Connection conn; 
    private String query;
    
    //custom objects
    private SystemClient_DBImpl userProfile;
    private ClassificationList classList;
    
    //query result objects
    private int rowCount;
    private ResultSet rs;
    
    //error message
    private String errMsg;
    
    /** Creates a new instance of ProfileHandler */
    public ProfileHandler() {
        errMsg = "no error";
        connectionPool = DBPool.getInstance();
        conn = connectionPool.getConnection();
    }
    public String HandleProfileRequest(HttpServletRequest request, HttpSession session){
        String profileAction = request.getParameter("profileAction");

// getProfile        
        if(profileAction.equals("getProfile")){
            
        // SECTION-BEGIN: get resultset of classifications
            ResultSet classRs = null;
            query = "SELECT * FROM classification";
            if(!this.RunSelectQuery(query)){
                session.setAttribute("message",this.errMsg);
                return "/jrs_error.jsp";
            }else{
                classRs = this.rs;
            }
        // SECTION-END: get resultset of classifications  
            
            
        // SECTION-BEGIN: get up-to-date profile
            userProfile = (SystemClient_DBImpl)session.getAttribute("userProfile");
            query = "SELECT * FROM person WHERE email='"+userProfile.getEmail()+"'";
            
            if(this.RunSelectQuery(query)){
                if(this.GetProfile()){
                    //session.setAttribute("userProfile",this.userProfile);
                }else{
                    session.setAttribute("message",this.errMsg);
                    return "/jrs_error.jsp";                         
                }
            }else{
                session.setAttribute("message",this.errMsg);
                return "/jrs_error.jsp";            
            }
        //SUB-SECTION-BEGIN: get classifications
            query = "SELECT * FROM person_has_classification WHERE "
                    +" person_personID='"+userProfile.getId()+"'";
            if(this.RunSelectQuery(query)){
                if(this.GetClassificationList()){
                    userProfile.setClassSet(this.classList);
                }else{
                    session.setAttribute("message",this.errMsg);
                    return "/jrs_error.jsp";                 
                }
            }else{
                session.setAttribute("message",this.errMsg);
                return "/jrs_error.jsp";              
            }
        //SUB-SECTION-END: get classifications 
        // SECTION-END: get up-to-date profile
            
            // set session object and return url to profile page
            session.setAttribute("classRs",classRs);
            session.setAttribute("userProfile",this.userProfile);
            return "/myprofile.jsp";

            
            
// updateProfile            
        }else if(profileAction.equals("updateProfile")){
            
            userProfile = (SystemClient_DBImpl)session.getAttribute("userProfile");     
            int personId = userProfile.getId();
            String classId;
            classList = new ClassificationList();

        // SECTION-BEGIN: get resultset of classifications
            ResultSet classRs = null;
            query = "SELECT * FROM classification";
            if(!this.RunSelectQuery(query)){
                session.setAttribute("message",this.errMsg);
                return "/jrs_error.jsp";
            }else{
                classRs = this.rs;
            }
        // SECTION-END: get resultset of classifications             
            
        // SECTION-BEGIN: get parameters from request object    
            String fname = (String)request.getParameter("fname");
            String lname = (String)request.getParameter("lname");
            String addr1 = (String)request.getParameter("addr1");
            String addr2 = (String)request.getParameter("addr2");
            String city = (String)request.getParameter("city");
            String state = (String)request.getParameter("state");
            String zip = (String)request.getParameter("zip"); 
            String phone = (String)request.getParameter("phone");
            String cell = (String)request.getParameter("cell");
            String dob = (String)request.getParameter("dob");
            String fontColor = (String)request.getParameter("fontColor");
            try {
                while(classRs.next()){
                    classId = (String)request.getParameter(classRs.getString("classificationID"));
                    if(classId!=null){
                        classList.AddClass(Integer.parseInt(classId));
                    }
                }
            } catch (SQLException ex) {
                session.setAttribute("message","get resultset of classifications:"+ex.toString());
                return "/jrs_error.jsp";
            }
        // SECTION-END: get parameters from request object
            
        // SECTION-BEGIN: update person table
            query = "UPDATE person SET "
                    +"fname='"+fname+"',lname='"+lname+"" 
                    +"',addr1='"+addr1+"',addr2='"+addr2+"',city='"+city 
                    +"',state='"+state+"',zip='"+zip+"',phone='"+phone 
                    +"',cell='"+cell+"',dob='"+dob+"',fontColor='"+fontColor
                    +"' WHERE personID="+personId;
            if(this.RunUpdateQuery(query)){
                // yippy! it worked!
            }else{
                session.setAttribute("message","update person table:"+this.errMsg);
                return "/jrs_error.jsp";             
            }
        // SECTION-END: update person table
        
        // SECTION-BEGIN: update classification table    
            query = "DELETE FROM person_has_classification WHERE "
                    +"person_personID="+personId;
            if(this.RunUpdateQuery(query)){
                try {
                    classRs.first();
                    while(classRs.next()){
                        if(classList.IsChecked(classRs.getInt("classificationID")).equals("checked")){
                            query="INSERT INTO person_has_classification"
                                    +"(person_personID,classification_classificationID)"
                                    +"VALUES("+personId+","+classRs.getInt("classificationID")+")";
                            if(this.RunUpdateQuery(query)){
                                // yay worky!
                            }else{
                                session.setAttribute("message","update classification table:"+this.errMsg);
                                return "/jrs_error.jsp";                             
                            }
                        }
                    }
                } catch (SQLException ex) {
                    session.setAttribute("message",ex.toString());
                    return "/jrs_error.jsp";
                }
            }else{
                session.setAttribute("message","update classification table:"+this.errMsg);
                return "/jrs_error.jsp";             
            }  
        // SECTION-BEGIN: update classification table    
            
            return "/AutismSiteMasterController?action=profile&profileAction=getProfile";
            
            
            
// catch everything else            
        }else{
            return "/portal.jsp";
        }
    }
    
// re-usable private methods 
    private boolean RunUpdateQuery(String query){
        try{
            statement = conn.createStatement();
            rowCount = statement.executeUpdate(query);
        }catch(SQLException ex){
            errMsg = "Error running the following query:\n"
                    + query + "\n"+"ERROR: "+ex;
            return false;
        }
        return true;
    }
    private boolean RunSelectQuery(String query){
        try{
            statement = conn.createStatement();
            rs = statement.executeQuery(query);
        }catch(SQLException ex){
            errMsg = "Error running the following query:\n"
                    + query + "\n"+"ERROR: "+ex;
            return false;
        }
        return true;        
    }
    private boolean GetProfile(){
            try {
                if(rs.next()){
                    userProfile.setId(rs.getInt("personID"));
                    userProfile.setFname(rs.getString("fname"));
                    userProfile.setLname(rs.getString("lname"));
                    userProfile.setAddr1(rs.getString("addr1"));
                    userProfile.setAddr2(rs.getString("addr2"));
                    userProfile.setCity(rs.getString("city"));
                    userProfile.setState(rs.getString("state"));
                    userProfile.setZip(rs.getString("zip"));
                    userProfile.setPhone(rs.getString("phone"));
                    userProfile.setCell(rs.getString("cell"));
                    userProfile.setEmail(rs.getString("email"));
                    userProfile.setPassword(rs.getString("passwd"));
                    userProfile.setFontColor(rs.getString("fontColor"));   
                    return true;
                }
            } catch (SQLException ex) {
                errMsg = "Error running the following query:\n"
                        + query + "\n"+"ERROR: "+ex;
                return false;
                }
            return false;
    }
    private boolean GetClassificationList(){
        this.classList = new ClassificationList();
        try {
            while(rs.next()){
                classList.AddClass(rs.getInt("classification_classificationID"));
            }
        } catch (SQLException ex) {
            errMsg = "Error running the following query:\n"
                    + query + "\n"+"ERROR: "+ex;
            return false;
        }        
        return true;
    }
}


